import sqlite3
import json
import os
from configs import DB_PATH

def export_questions_to_json(db_path, output_path):
    try:
        # 连接到数据库
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        print(f"已连接到数据库: {db_path}")

        # 查询所有题目
        cursor.execute("SELECT * FROM questions ORDER BY id")
        rows = cursor.fetchall()
        print(f"查询到 {len(rows)} 道题目")

        # 获取列名
        column_names = [desc[0] for desc in cursor.description]

        # 格式化数据
        questions = []
        for row in rows:
            question = dict(zip(column_names, row))
            # 确保type字段是字符串类型
            question['type'] = str(question['type'])
            # 确保LA, LB, LC是字符串类型
            question['LA'] = str(question['LA'])
            question['LB'] = str(question['LB'])
            question['LC'] = str(question['LC'])
            # 去除I字段中的空格
            if 'I' in question:
                question['I'] = question['I'].replace(' ', '')
            # 如果F字段为空，设置为null
            if not question['F']:
                question['F'] = None
            questions.append(question)

        # 关闭数据库连接
        conn.close()

        # 写入JSON文件
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(questions, f, ensure_ascii=False, indent=4)
        print(f"数据已导出到: {output_path}")
        return True
    except Exception as e:
        print(f"导出数据时出错: {e}")
        return False

if __name__ == "__main__":
    db_path = DB_PATH
    output_path = r"c:\Users\Draczz\Desktop\crac_exam\data\tk.json"
    
    # 检查数据库文件是否存在
    if not os.path.exists(db_path):
        print(f"数据库文件不存在: {db_path}")
    else:
        # 导出数据
        success = export_questions_to_json(db_path, output_path)
        if success:
            print("导出成功")
        else:
            print("导出失败")